# -*- coding: utf-8 -*-
import gitee_package
import log_package
import ini_package
import pandas_package
from playwright_package import os_package
from gitee_package import re
from playwright_package import time_package
import playwright_package
import excel_package


# 获取gitee数据
def get_gitee_data():
    global ini_opt
    try:
        # 连接gitee获取基本数据
        gitee_opt = gitee_package.Gitee_Option('https://gitee.com/zl_b/file_config.git',
                                               "06fbfe091fc755b51084d86966a14cc6")
        main_repo_data = gitee_opt.list_all_files_and_folders('金牛区相关信息')

        # 获取ini数据
        url = main_repo_data.get("重要配置.ini")
        if url:
            da = gitee_opt.get_gitee_repo_file(url)
            if da:
                ini_opt.read_ini_string(da)
                log_opt.write_success(f'成功获取gitee数据，【重要配置.ini】信息成功！')
                return True
            else:
                raise Exception('获取【重要配置.ini】信息失败！')
        else:
            raise Exception('未找到-【重要配置.ini】！')

    except Exception as e:
        log_opt.write_error(f'获取gitee出现错误{e}')
        return False


# 分析记录
def analysis_record_1(file_path):
    ex = excel_package.Excel_Option(file_path)
    ex_1 = excel_package.Excel_Option('file/课时统计.xlsx')
    ex_1.create_new_excel()
    ex_1.delete_sheet('Sheet')
    ex_1.create_new_sheet('统计信息')
    ex.open_file()
    sheet_name = ex.list_sheets()[0]
    pd = pandas_package.Big_Data_Option()
    pd.open_file(file_path, sheet_name)
    pd.data_deduplication()
    # print(pd.data_handle)
    teacher_names = list(set(pd.view_specific_column('教师姓名', is_tolist=True)))
    teacher_names.sort(reverse=True)
    headers = pd.get_column_names()
    # print(headers)
    course_dict = dict()
    try:
        for teacher_name in teacher_names:
            t_data = pd.view_filtered_data({'教师姓名': f'{teacher_name}'})
            if t_data:
                pd_1 = pandas_package.Big_Data_Option()
                pd_1.list_to_dataframe(t_data)
                course_dict[teacher_name] = sum(pd_1.view_specific_column('课时数', True))
                # print(t_data)
                ex_1.create_new_sheet(teacher_name)
                ex_1.write_headers_to_sheet(teacher_name, headers)
                a = 2
                for td in t_data:
                    ex_1.insert_row_values(teacher_name, a, td)
                    a += 1
        # print(course_dict)
        # ex_1.create_new_sheet('统计信息')
        ex_1.write_headers_to_sheet('统计信息', ['教师姓名', '课时数'])
        a = 2
        for c, d in course_dict.items():
            ex_1.insert_row_values('统计信息', a, {'教师姓名': c, '课时数': d})
            a += 1
        return True
    except Exception as e:
        return False
    finally:
        ex_1.save_file()
        ex_1.close_file()
        ex.close_file()


def analysis_record(file_path):
    ex = excel_package.Excel_Option(file_path)
    ex_1 = excel_package.Excel_Option('file/课时统计.xlsx')
    ex_1.create_new_excel()
    ex_1.delete_sheet('Sheet')
    ex_1.create_new_sheet('统计信息')
    ex.open_file()
    sheet_name = ex.list_sheets()[0]
    pd = pandas_package.Big_Data_Option()
    pd.open_file(file_path, sheet_name)
    pd.data_deduplication()
    # print(pd.data_handle)
    teacher_names = list(set(pd.view_specific_column('教师姓名', is_tolist=True)))
    teacher_names.sort(reverse=True)
    headers = pd.get_column_names()
    # print(headers)
    course_dict = dict()
    try:
        for teacher_name in teacher_names:
            t_data = pd.view_filtered_data({'教师姓名': f'{teacher_name}'})
            # print(t_data)
            course_dict[teacher_name] = 0
            if t_data:
                for row_data in t_data:
                    # print(row_data)
                    if int(row_data['学生人数']) >= 60:
                        course_dict[teacher_name] += float(row_data['课时数']) * 2
                    elif int(row_data['学生人数']) >= 50:
                        course_dict[teacher_name] += float(row_data['课时数']) * 1.5
                    else:
                        course_dict[teacher_name] += float(row_data['课时数']) * 1
                # print(course_dict)
                ex_1.create_new_sheet(teacher_name)
                ex_1.write_headers_to_sheet(teacher_name, headers)
                a = 2
                for td in t_data:
                    ex_1.insert_row_values(teacher_name, a, td)
                    a += 1
        ex_1.write_headers_to_sheet('统计信息', ['教师姓名', '课时数'])
        a = 2
        for c, d in course_dict.items():
            ex_1.insert_row_values('统计信息', a, {'教师姓名': c, '课时数': d})
            a += 1
        return True
    except Exception as e:
        return False
    finally:
        ex_1.save_file()
        ex_1.close_file()
        ex.close_file()


if __name__ == '__main__':
    print('''请选择模式\n[0]:仅下载课时记录\n[1]:下载并分析课时记录\n[2]:仅分析课时记录\n为空或者其他值默认为0''')
    user_select_mode = input('请输入您要选择的模式：\n')
    try:
        user_select_mode = int(user_select_mode)
    except Exception as e:
        user_select_mode = 0
    # 初始化
    time_opt = time_package.Time_Option()
    time_opt.start_timing()
    log_opt = log_package.Logging_Option()
    log_opt.write_info('正在初始化...')
    ini_opt = ini_package.Config_Option()
    os_opt = os_package.Os_Option()
    os_opt.make_file_folder('file')
    os_opt.make_file_folder('log')
    log_opt.write_success('初始化成功！')

    # 获取gitee数据
    if user_select_mode == 1:
        log_opt.write_info('正在获取gitee数据...')
        try:
            if get_gitee_data():
                log_opt.write_success('获取gitee数据成功！')
                zh = ini_opt.get_section_option('教学管理系统', 'zh')
                mm = ini_opt.get_section_option('教学管理系统', 'mm')
                if zh and mm:
                    # todo 获取教学记录管理系统
                    log_opt.write_info('正在登陆教学记录管理系统...')
                    plw_opt = playwright_package.Playwright_Management()
                    if plw_opt.teaching_record_system_login(zh, mm):
                        log_opt.write_success('登陆教学记录管理系统成功！')
                        start_date = ini_opt.get_section_option('教学管理系统', 'start_date')
                        end_date = ini_opt.get_section_option('教学管理系统', 'end_date')
                        if start_date and end_date:
                            if plw_opt.teaching_record_system_course_data_download(start_date, end_date,
                                                                                   'file/课时记录.xlsx'):
                                log_opt.write_success(
                                    f'下载{start_date}-{end_date}的课时记录至【file/课时记录.xlsx】成功！')
                                plw_opt.close()

                                log_opt.write_info('正在分析【file/课时记录.xlsx】...')
                                if analysis_record('file/课时记录.xlsx'):
                                    log_opt.write_success('分析【file/课时记录.xlsx】- 已生成【file/课时统计.xlsx】成功！')
                                else:
                                    raise Exception('分析【file/课时记录.xlsx】出错！')
                            else:
                                raise Exception(f'下载{start_date}-{end_date}的课时记录至【file/课时记录.xlsx】失败！')
                        else:
                            raise Exception('未获取到【教学管理系统】的开始日期和结束日期，请联系管理员查看云端！')
                    else:
                        log_opt.write_error('登陆教学记录管理系统失败！')
                        raise Exception('获取教学记录管理系统数据失败')
                else:
                    raise Exception('未获取到【教学管理系统】的账号和密码，请联系管理员查看云端！')
            else:
                raise Exception('获取gitee数据失败!')
        except Exception as e:
            log_opt.write_error(f'程序异常：{e}')
        finally:
            log_opt.write_info(f'程序用时：{time_opt.end_timing()}')
            time_opt.timesleep(3)
    elif user_select_mode == 2:
        try:
            # 分析记录
            log_opt.write_info('正在分析【file/课时记录.xlsx】...')
            if analysis_record('file/课时记录.xlsx'):
                log_opt.write_success('分析【file/课时记录.xlsx】- 已生成【file/课时统计.xlsx】成功！')
            else:
                raise Exception('分析【file/课时记录.xlsx】出错！')
        except Exception as e:
            log_opt.write_error(f'程序异常：{e}')
        finally:
            log_opt.write_info(f'程序用时：{time_opt.end_timing()}')
            time_opt.timesleep(3)
    else:
        log_opt.write_info('正在获取gitee数据...')
        try:
            if get_gitee_data():
                log_opt.write_success('获取gitee数据成功！')
                zh = ini_opt.get_section_option('教学管理系统', 'zh')
                mm = ini_opt.get_section_option('教学管理系统', 'mm')
                if zh and mm:
                    # todo 获取教学记录管理系统
                    log_opt.write_info('正在登陆教学记录管理系统...')
                    plw_opt = playwright_package.Playwright_Management()
                    if plw_opt.teaching_record_system_login(zh, mm):
                        log_opt.write_success('登陆教学记录管理系统成功！')
                        start_date = ini_opt.get_section_option('教学管理系统', 'start_date')
                        end_date = ini_opt.get_section_option('教学管理系统', 'end_date')
                        if start_date and end_date:
                            if plw_opt.teaching_record_system_course_data_download(start_date, end_date,
                                                                                   'file/课时记录.xlsx'):
                                log_opt.write_success(
                                    f'下载{start_date}-{end_date}的课时记录至【file/课时记录.xlsx】成功！')
                                plw_opt.close()
                            else:
                                raise Exception(f'下载{start_date}-{end_date}的课时记录至【file/课时记录.xlsx】失败！')
                        else:
                            raise Exception('未获取到【教学管理系统】的开始日期和结束日期，请联系管理员查看云端！')
                    else:
                        log_opt.write_error('登陆教学记录管理系统失败！')
                        raise Exception('获取教学记录管理系统数据失败')
                else:
                    raise Exception('未获取到【教学管理系统】的账号和密码，请联系管理员查看云端！')
            else:
                raise Exception('获取gitee数据失败!')
        except Exception as e:
            log_opt.write_error(f'程序异常：{e}')
        finally:
            log_opt.write_info(f'程序用时：{time_opt.end_timing()}')
            time_opt.timesleep(3)
    log_opt.write_success('程序执行完毕！')
